//
//  HCHomeTableViewController.swift
//  新浪微博
//
//  Created by fanhoucheng on 16/9/22.
//  Copyright © 2016年 fanhoucheng. All rights reserved.
//

import UIKit
import SVProgressHUD

class HCHomeTableViewController: HCBaseTableViewController {
    
    lazy var homeViewModel: HCHomeViewModel = HCHomeViewModel()
    let hcRefreshControl = HCRefreshControl()

    //实例化一个小菊花视图
    lazy var indicatorView: UIActivityIndicatorView = {
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
        
        
        return indicator
    }()
    
    //实例化一个下拉刷新提示label
    lazy var tipLabel: UILabel = {
        let label = UILabel(title: "", textColor: UIColor.white, fontSize: 14)
        
        label.backgroundColor = UIColor.orange
        label.textAlignment = .center
        label.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 35)
        //label.alpha = 0
        label.isHidden = true
        
        return label
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        //添加left
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(push))
        
        visitorView.updateUI(describeLableName: "关注一些人,快回到这里看看有什么惊喜", imageName: nil)
        
        //注册原创nib
        let StatusNib = UINib(nibName: "HCStatusCell", bundle: nil)
        self.tableView.register(StatusNib, forCellReuseIdentifier: "HCStatusCellId")
        
        //注册转发nib
        let RetweetedNib = UINib(nibName: "HCRetweetedStatus", bundle: nil)
        self.tableView.register(RetweetedNib, forCellReuseIdentifier: "HCRetweetedStatusId")
        tableView.rowHeight = 560
        tableView.separatorStyle = .none
        
        loadData()
        
        tableView.tableFooterView = indicatorView
        
//        refreshControl = UIRefreshControl()
//        refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
        
        hcRefreshControl.addTarget(self, action: #selector(loadData), for: .valueChanged)
        self.view.addSubview(hcRefreshControl)
        //indicatorView.startAnimating()
        //设置提醒label
        tipLabel.frame.origin.y = 64 - 35

        self.navigationController?.view.addSubview(tipLabel)
        self.navigationController?.view.insertSubview(tipLabel, belowSubview: self.navigationController!.navigationBar)
        

    }
    
    func loadData() {
        homeViewModel.loadHomeModel(isPullup: indicatorView.isAnimating) { (result, count) in
            if !result {
                SVProgressHUD.showError(withStatus: errorTip)
                return
            }
            //self.refreshControl?.endRefreshing()
            //self.hcRefreshControl.refreshStatue = .Normal
            self.hcRefreshControl.stopAnimation()
            self.indicatorView.stopAnimating()
            //数据加载完成时,开启动画效果
            self.startTipLabelAnimation(count: count)
            self.tableView.reloadData()
        }
        
    }
    
    func startTipLabelAnimation(count: Int) {
        self.tipLabel.text = count == 0 ? "没有新微博数据" : "有\(count)条新微博数据"
        self.tipLabel.isHidden = false
        let lastY = self.tipLabel.frame.origin.y
        //开启动画
        UIView.animate(withDuration: 1, animations: {
            self.tipLabel.frame.origin.y = 64
            }) { (_) in
                UIView.animate(withDuration: 1, delay: 1, options: [], animations: { 
                    self.tipLabel.frame.origin.y = lastY
                    }, completion: { (_) in
                        self.tipLabel.isHidden = true
                })
        }
    }
    
    @objc private func push() {
        let tempView = HCTempViewController()
        self.navigationController?.pushViewController(tempView, animated: true)
    }

}

extension HCHomeTableViewController {
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        //多少行
        return homeViewModel.statusViewModelArray.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //获取数据
        let viewModel = homeViewModel.statusViewModelArray[indexPath.row]
        
        let cellId = getCellId(viewModel: viewModel)
        //返回cell
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! HCStatusCell
        
        cell.viewModel = viewModel
        cell.selectionStyle = .none
        
        return cell
    }
    
    func cellWithId(cellId: String) ->HCStatusCell {
        var nibName: String
        if cellId == "HCStatusCellId" {
            nibName = "HCStatusCell"
        } else {
            nibName = "HCRetweetedStatus"
        }
        return UINib(nibName: nibName, bundle: nil).instantiate(withOwner: nil, options: nil).last as! HCStatusCell
    }
    
    func getCellId(viewModel: HCStatusViewModel) -> String {
        if viewModel.status?.retweeted_status == nil {
            return "HCStatusCellId"
        }
        //返回转发微博
        return "HCRetweetedStatusId"
    }
    
    //返回行高,得先布局,填充模型数据,然后返回行高
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        //1.先创建一个cell,然后填充数据,然后布局
        let viewModel = homeViewModel.statusViewModelArray[indexPath.row]
        
        let cellId = getCellId(viewModel: viewModel)
        
        let cell = cellWithId(cellId: cellId)
        
        return cell.rowHeight(viewModel: viewModel)
    }
    
    //代理方法实现什么时候开启小菊花转动
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indexPath.row == homeViewModel.statusViewModelArray.count - 2 && indicatorView.isAnimating == false {
            indicatorView.startAnimating()
            loadData()
        }
        
    }
    
}

